import json

from django.http import HttpResponseBadRequest

from home.models import Article, ArticleCategory


def commin_date(request):

    hot_tags = Article.objects.all().order_by('-total_views').distinct()[:9]

    new_arts = Article.objects.order_by("-create_time")[:2]

    # 1、获取所有分类信息数据
    categories = ArticleCategory.objects.all()
    # 2、接收用户点击的分类id
    cat_id = request.GET.get('cat_id', 1)
    # 3、根据分类id进行分类的查询
    try:
        category = ArticleCategory.objects.get(id=cat_id)
    except ArticleCategory.DoesNotExist:
        # category = ArticleCategory.objects.get(id=1)

        return HttpResponseBadRequest('此分类信息不存在')

    # 5、根据分类信息查询该分类下的所有文章数据
    articles = Article.objects.filter(category=category)

    if request.COOKIES.get("login_name") is not None:
        username = json.loads(request.COOKIES.get('login_name'))
    else:
        username = ""

    return {
        "hotTags": hot_tags,
        "newArt": new_arts,
        'categories': categories,
        'category': category,
        'username': username,
    }